package com.ryskoo.permission.dept.service;

import com.ryskoo.framework.core.service.BasicServiceImpl;
import com.ryskoo.permission.dept.domain.DeptPO;
import com.ryskoo.permission.dept.repository.IDeptRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author Shawn
 */
@Service
@Transactional
public class DeptServiceImpl extends BasicServiceImpl<DeptPO> implements
		IDeptService {
	@Autowired
	private IDeptRepository deptRepository;

	@PostConstruct
	public void init() {
		this.setDao(deptRepository);
	}

	/**
	 * 根据父部门获取子部门集合
	 */
	@Override
	public List<DeptPO> getByParentId(String parentId) {
		List<DeptPO> list = deptRepository.getByParentId(parentId);
		// 获取部门下的子部门
		if (list != null && list.size() > 0) {
			for (DeptPO deptPO : list) {
				List<DeptPO> chilrenList = deptRepository.getByParentId(deptPO
						.getUuid());
				deptPO.setChildrens(chilrenList);
			}
		}
		
		return list;
	}

	/**
	 * 部门递归获取子部门
	 * 
	 * @param list
	 * @return
	 */
	public List<DeptPO> getAllDepts(List<DeptPO> list) {
		if (list != null && list.size() > 0) {
			for (DeptPO deptPO : list) {
				List<DeptPO> chilrenList = deptRepository.getByParentId(deptPO
						.getUuid());
				deptPO.setChildrens(chilrenList);
				getAllDepts(chilrenList);
			}
		}
		return list;
	}

	@Override
	public List<DeptPO> getDeptByParentIdAndSalesManId(String parentId, String salesManId) {
		//1.校验参数
		if(StringUtils.isBlank(salesManId)){
			return null;
		}
		//2.根据父级部门id、所属人Id查询子部门
		List<DeptPO> list = deptRepository.getDeptByParentIdAndSalesManId(parentId, salesManId);
		//3.获取部门下的子部门
		if (list != null && list.size() > 0) {
			for (DeptPO deptPO : list) {
				List<DeptPO> chilrenList = deptRepository.getDeptByParentIdAndSalesManId(deptPO
						.getUuid(),salesManId);
				deptPO.setChildrens(chilrenList);
			}
		}
		return list;
	}
}
